package com.lc202407;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class Solution697 {
    public int findShortestSubArray(int[] nums) {
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int num : nums) {
            int i = map.getOrDefault(num, 0) + 1;
            map.put(num, i);
        }
        int max = map.values().stream().max(Integer::compare).get();
        ArrayList<Integer> numbers = new ArrayList<>();
        for (Map.Entry<Integer, Integer> integerIntegerEntry : map.entrySet()) {
            if (integerIntegerEntry.getValue() == max) {
                numbers.add(integerIntegerEntry.getKey());
            }
        }
        int res = Integer.MAX_VALUE;
        for (Integer number : numbers) {
            int start = 0;
            int end = 0;
            int length = nums.length;
            for (int i = 0; i < length; i++) {
                if (number == nums[i]) {
                    start = i;
                    break;
                }
            }
            for (int i = 0; i < length; i++) {
                if (number == nums[length - i - 1]) {
                    end = length - i - 1;
                    break;
                }
            }
            res = Math.min(res, end - start + 1);
        }
        return res;
    }
}
